package com.dwxt.mall.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.IDUtils;
import com.dwxt.common.wxpay.MyWXPayConfig;
import com.dwxt.common.wxpay.WXPay;
import com.dwxt.common.wxpay.WXPayUtil;
import com.dwxt.mall.constant.OrderStatus;
import com.dwxt.mall.entity.PayOrder;
import com.dwxt.mall.entity.Product;
import com.dwxt.mall.service.feign.PayService;
import com.dwxt.mall.service.feign.RedisService;
import com.dwxt.mall.service.feign.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WXService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private PayService payService;

    @Autowired
    private UserService userService;

    @Value("${mall.wx.notifyUrl}")
    public String notifyUrl;

    @Transactional
    public BaseResult createOrderWithWX(PayOrder order, String ip, HttpServletRequest request) throws Exception {
        //校验订单参数
        Product product = productService.selectProductByPrimaryKey(order.getProductId());
        BaseResult result = orderService.validOrder(order, product);
        if (result != null) {
            return result;
        }
        //生成微信预付订单
        String orderId = IDUtils.genItemId();
        Double realPrice = order.getRealPrice();
        Map<String, String> respData = new HashMap<>();
        if (realPrice > 0) {
            //respData = createPaymentOrderReadyWX(order, ip, null);
            //构造请求参数，请求微信支付
            Map<String, String> params = buildReqParams(request, orderId, realPrice);
            BaseResult baseResult = payService.payWithWX(params);
            respData = (Map) baseResult.getData();
            //生成本地订单
            orderService.createOrderLocal(order, product, orderId, respData);
            //订单存入redis
            redisService.set("mall_" + order.getId(), order.getId(), (long) 15 * 60);
        } else {
            //生成本地订单
            orderService.createOrderLocal(order, product, orderId, respData);
            //更改用户积分，生成积分记录,消耗积分
            userService.updateIntegral(-order.getIntegral(), order.getId(), order.getName(), order.getUserId());
        }
        return BaseResult.ok(respData);
    }

    private Map<String, String> buildReqParams(HttpServletRequest request, String orderId, Double realPrice) {
        String ip = request.getRemoteAddr();
        String type = request.getParameter("type");
        String openid = request.getParameter("openid");

        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderId);
        if (StringUtils.isBlank(type)) {
            params.put("type", "1");
        } else {
            params.put("type", type);
        }
        if (StringUtils.isNotBlank(openid)) {
            params.put("openid", openid);
        }
        params.put("ip", ip);
        params.put("notifyUrl", notifyUrl);
        params.put("price", realPrice.toString());
        return params;
    }


    @Transactional
    public String payBack(String notifyData) throws Exception {
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        MyWXPayConfig myWXPayConfig = new MyWXPayConfig();
        WXPay wxpay = new WXPay(myWXPayConfig);
        notifyMap = WXPayUtil.xmlToMap(notifyData);         // 转换成map
        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            String return_code = notifyMap.get("return_code");//状态
            String out_trade_no = notifyMap.get("out_trade_no");//订单号
            PayOrder order = orderService.selectByPrimaryKey(out_trade_no);
            if (out_trade_no == null || !return_code.equalsIgnoreCase("SUCCESS")) {
                log.info("微信支付回调失败订单号: {}", notifyMap);
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                        "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                //库存增加,订单失败
                orderService.cancelOrfailOrder(order, OrderStatus.Fail);
                return xmlBack;
            } else {
                xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" +
                        "<return_msg><![CDATA[SUCCESS]]></return_msg>" + "</xml> ";
                if (!order.getStatus().equalsIgnoreCase(OrderStatus.PLACE)) {
                    return xmlBack;
                }
                // 业务逻辑处理 ****************************
                //更改订单状态
                orderService.changUserInfoWithWxAndZFBPay(order);
                log.info("微信支付回调成功订单号: {}", notifyMap);
                return xmlBack;
            }
        } else {
            log.error("微信支付回调通知签名错误");
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return xmlBack;
        }
    }

}
